package com.holystone.orca.sys.controller;

import com.holystone.orca.base.controller.BaseController;
import com.holystone.orca.sys.aop.SystemControllerBeforeLog;
import com.holystone.orca.sys.aop.SystemControllerLog;
import com.holystone.orca.sys.common.SystemConstant;
import com.holystone.orca.sys.model.LoginVO;
import com.holystone.orca.sys.model.MenuNavVO;
import com.holystone.orca.sys.model.StaffVO;
import com.holystone.orca.sys.mybatis.model.SysPerson;
import com.holystone.orca.sys.service.ILoginService;
import com.holystone.orca.sys.service.ISysOperationLogService;
import com.holystone.orca.sys.service.ISysPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * 登录控制 
 * 项目名称：ORCA 
 * 类名称：LoginController 
 * 创建人：王凯征 
 * 创建时间：2015-10-14 上午07:51:46
 * @version ORCA-v4.0.0
 */
@Controller
@RequestMapping(value = "/framework/")
public class LoginController extends BaseController {
	private static String LOGIN_KEY = "loginKey";
	@Autowired
	private ILoginService loginService; 

	@Resource(name="sysOperationLogService")
	private ISysOperationLogService sysOperationLogService;
	@Autowired
	private ISysPersonService sysPersonService;

	@Value("#{properties.socketIp}")
	private String socketIp;
	@Value("#{properties.socketPort}")
	private String socketPort;
	/**
	 * @desc: 获取登录的key
	 * @author: 王凯征
	 * @date: 2015年11月4日 下午4:58:54
	 * @return
	 */
	@RequestMapping(value = "ajaxLoginKey")
	public @ResponseBody ModelMap ajaxLoginKey() {
		Date time = new Date();
		long tm = time.getTime();
		long rdm = (long) (Math.random() * 1000000000);
		long ramdomkey = tm + rdm;

		super.session().setAttribute(LoginController.LOGIN_KEY, ramdomkey);
		ModelMap map = new ModelMap();
		map.put("key", ramdomkey);
		return map;
	}

	/**
	 * @desc:登录信息校验
	 * @author: guanzhichao
	 * @date:2016年1月25日 下午4:12:41
	 * @Param: loginVO
	 * @Param: model
	 * @return: ModelMap
	 */
	@RequestMapping(value="checkLoginInfo")
	@ResponseBody
	public ModelMap checkLoginInfo(LoginVO loginVO,HttpServletRequest request){
//		UsernamePasswordToken token = new UsernamePasswordToken(loginVO.getPersonCode(), loginVO.getPersonPassword());  
//        Subject subject = SecurityUtils.getSubject();
//        boolean rememberMe = ServletRequestUtils.getBooleanParameter(request, "rememberMe", false);  
//        try{
//        	subject.login(token);
//        	System.out.println("===========登录============");
//        }catch(Exception e){
//        	System.out.println("===========登录异常============");
//        }
//        if(subject.isAuthenticated()){
//        	System.out.println("===========登录============");
//        }else{
//        	System.out.println("===========登录异常============");
//        }
		ModelMap modelMap = new ModelMap();
		Long key = (Long) super.session().getAttribute(LOGIN_KEY);
		boolean isPersonExist = this.loginService.isPersonExist(
				loginVO.getPersonCode(), loginVO.getPersonPassword(), key);
		
		// 员工存在
		if (isPersonExist) {
			StaffVO staffVO = this.loginService.initStaffVO(loginVO.getPersonCode());
			// 人员被关闭
			if (SystemConstant.PERSON_STATE_B.equals(staffVO.getPersonState())) {
				super.setErrorMsg(SystemConstant.LOGIN_PERSON_BAN);
				modelMap.put("flag", "用户被锁定,请联系管理员！");
				return modelMap;
				// 人员未被关闭
			} else {
				// 未分配权限
				if (staffVO.getPrivilegeList().size() == 0) {
					super.setErrorMsg(SystemConstant.LOGIN_PERSON_NO_PRI);
					modelMap.put("flag", "账号已冻结，请联系管理员");
					return modelMap;
				}
			}
			// 员工不存在
		} else {
			super.setErrorMsg(SystemConstant.LOGIN_NAME_ERROR);
			modelMap.put("flag", "用户账号或密码错误！");
			return modelMap;
		}
		modelMap.put("flag", true);
		return modelMap;
	}
	
	/**
	 * 初始化首页
	 */
	@RequestMapping("login")
	public ModelAndView login() {
		ModelAndView modelView = new ModelAndView("/framework/login");
		return modelView;
	}
	
	/**
	 * @desc: 成功登录
	 * @author: guanzhichao
	 * @date: 2016年1月25日 
	 * @Param: staffVO
	 * @Param: model
	 * @return: String
	 */
	@RequestMapping(value = "/loginSuccess")
	@ResponseBody
	@SystemControllerLog(description = "登录")
	public ModelAndView loginSuccess(LoginVO loginVO) {
		ModelAndView view = new ModelAndView("framework/index");
		StaffVO staffVO = null;
		staffVO = loginService.initStaffVO(loginVO.getPersonCode());
		
		if(staffVO == null){
			return new ModelAndView("/framework/login");
		}
		String defaultMenuId  = loginService.getDefaultTopMenuRootId(staffVO.getPrivilegeList());
		staffVO.setDefaultMenuId(defaultMenuId);
		view.addObject("defaultMenuId", defaultMenuId);
		SysPerson person = sysPersonService.selectByPersonId(staffVO.getPersonId().toString());
		super.session().invalidate();
		// 将用户对象放入session
		super.session().setAttribute(SystemConstant.SESSION_STAFF_KEY, staffVO);// 将员工对象存入SESSION
		List<MenuNavVO> menuNavList = loginService.getMenuNavVOList(staffVO.getPrivilegeList());
		view.addObject("personName", person.getPersonName());
		view.addObject("menuNavList", menuNavList);
		view.addObject("staffId", getCurrentStaffId());
		//不能向后台传递变量名为“socketIp”“socketPort”，前台页面获取不到,改为“serverIp”，“serverPort”
        view.addObject("serverIp", socketIp);
        view.addObject("serverPort", socketPort);
        return view;
	}

	@RequestMapping("logout")
	@SystemControllerBeforeLog(description = "注销")
	public String logout(){
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession contextSess = attr.getRequest().getSession(true);
        contextSess.invalidate();
		return "/framework/login";
	}
	/**
	 * 联系我们
	 * @author: 李海宁
	 * @date: 2016年7月6日 上午10:17:23
	 * @return String
	 */
	@RequestMapping(value="connectUs")
	public String connectUs(){
		return "/framework/contact";
	}
	/**
	 * 凭证管理
	 * @author: 李海宁
	 * @date: 2016年7月6日 上午11:28:41
	 * @return
	 */
	@RequestMapping(value="licenceManager")
	public String licenceManager(){
		return "/framework/importLicence";
	}
	public ILoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}

}